package com.sendpo.zjx.sendpo.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.*;
import android.view.WindowManager;

import com.amap.api.maps.model.LatLng;

import org.xutils.DbManager;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/10/20.
 */

 public final class Tools {
   public static final String ISALLOWSHOWDOWNLOAD="ISALLOWSHOWDOWNLOAD";
    public static  final String  CALL="call";
    public static  final String ISFIRSTSTARTING="isFirstStarting";
    //配置名称
    public static  final String CONFIG="config";
    public static  final  String FIRSTRUNNING="firstrunning";
    //账号
    public static  final String NICKNAME="nickname";
    //密码
    public static  final String PASSWORD="password";
    public static  final String CHECK_REMEMVER="checkbox_remember";
    //自动登录
    public static  final String CHECK_AUTOLOGIN="checkbox_autologin";
    public static  final String DBNAME="sendpo";
    public static  final int DBVERSION=1;

      public static  final String SEX="select_sex";
     public  static  final String START_AGE="selecct_start_age";
    public  static  final String END_AGE="selecct_end_age";
/*
  * 判断是否为整数
  * @param str 传入的字符串
  * @return 是整数返回true,否则返回false
*/


    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }




    //判断是否大于4.4
    public static boolean isJudgementVersion(){
           boolean isFlag=false;
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){
                isFlag=true;
            }
         return  isFlag;
     }
    //得到屏幕长宽
    public static DisplayMetrics getDisplay(Context context){
                    WindowManager windowManager= (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics=new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);

        return displayMetrics;
    }
    //设置缓存
    public static void setCache(Activity activity, String url, String json){
           SharedPreferences.Editor editor=activity.getSharedPreferences("cache",Context.MODE_PRIVATE).edit();
         editor.putString(url,json);
        editor.commit();
    }
    //得到缓存
    public static String getCache(Activity activity,String url){
         String json=null;
       SharedPreferences sp=activity.getSharedPreferences("cache",Context.MODE_PRIVATE);
             json=sp.getString(url,null);
        return  json;
    }
//得到连接状态类型
   public static int getConnectionState(Context context){
               ConnectivityManager cm= (ConnectivityManager) context.getSystemService(Service.CONNECTIVITY_SERVICE);
                 NetworkInfo info=cm.getActiveNetworkInfo();

               if(info==null){
                   return 404;
               }else{
                    return  info.getType();
               }
   }
//转换时间
   public static  Long getStringtoDate(String time,String formattime){
       SimpleDateFormat simpleDateFormat=new SimpleDateFormat(formattime);
       Date date=new Date();;
       try {
           date=simpleDateFormat.parse(time);
       } catch (ParseException e) {
          return date.getTime();
       }
       return date.getTime();
   }
      //返回字符串时间
    public static  String getDateBeforeAfter(long datetime){
             StringBuffer sb=new StringBuffer();
        long time=System.currentTimeMillis()-(datetime);
          long mill= (long) Math.ceil(time/1000.0f);
         long min= (long) Math.ceil(time/1000/60.0f);
       long  hour= (long) Math.ceil(time/1000/60/60.0f);
        long  day= (long) Math.ceil(time/1000/60/60/24.0f);
        long month=(long) Math.ceil(time/1000/60/60/24/30.0f);
       if(month-1>0){
           if(month>12){
               sb.append("很久很久");
           }else if(month==12){
               sb.append("1年");
           }else{
               sb.append(month+"个月");
           }
       }else if(day-1>0){
             if(day==30){
                 sb.append("1个月");
             }else{
                 sb.append(day + "天");
             }

        }else if(hour-1>0){
              if(hour==24){
                  sb.append("1天");
              }else{
                  sb.append(hour+"小时");
              }
        }else if(min-1>0){
              if(min==60){
                  sb.append(hour+"1小时");
              }else{
                  sb.append(min+"分");
              }
        }else if(mill-1>0){
            if (mill == 60) {
                sb.append("1分钟");
            } else {
               sb.append(mill+"秒");
            }
        }else{
            sb.append("刚刚");
        }
         if(!sb.toString().equals("刚刚")){
             sb.append("前");
         }

        return sb.toString();
    }

//得到SQLite数据库管理对象
    public static DbManager getDbManager(Application application, String dbname, int dbversion){
         x.Ext.init(application);
        DbManager.DaoConfig config=new DbManager.DaoConfig();
        config.setDbName(dbname);
        config.setDbVersion(dbversion);
        config.setAllowTransaction(true);
        config.setDbOpenListener(new DbManager.DbOpenListener() {
            @Override
            public void onDbOpened(DbManager db) {
                db.getDatabase().enableWriteAheadLogging();
            }
        });
    return  x.getDb(config);
    };

    //得到APP版本号
    public static  int getVersionCode(Context context){
      int code=1;
        try {
            PackageInfo info=context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            code=info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return code;
    }

  //保存数据
    public static boolean setSharedPreference(Context context, String name,Map<String,Object> map){
       SharedPreferences.Editor editor=context.getSharedPreferences(name,Context.MODE_PRIVATE).edit();
               Iterator<Map.Entry<String, Object>> entryIterator=map.entrySet().iterator();
                                        while(entryIterator.hasNext()){
                                             Map.Entry entry=entryIterator.next();
                                                 if(entry.getValue() instanceof  String){
                                                     editor.putString(entry.getKey().toString(),entry.getValue().toString());
                                                 }else if(entry.getValue() instanceof Integer){
                                                     editor.putInt(entry.getKey().toString(),Integer.parseInt(entry.getValue().toString()));
                                                 }else if(entry.getValue() instanceof  Boolean){
                                                        editor.putBoolean(entry.getKey().toString(),Boolean.parseBoolean(entry.getValue().toString()));
                                                 }else if(entry.getValue() instanceof  Float){
                                                     editor.putFloat(entry.getValue().toString(),Float.parseFloat(entry.getValue().toString()));
                                                 }
                                        }

             return editor.commit();
    }
   //得到数据
    public static  SharedPreferences getSharedPreference(Context context,String name){
       return context.getSharedPreferences(name,Context.MODE_PRIVATE);
   };
  //得到数据MAP
   public static Map<String,Object> getSharedPreferenceMap(Context context,String name){
      SharedPreferences preferences=context.getSharedPreferences(name,Context.MODE_PRIVATE);
          return (Map<String, Object>) preferences.getAll();
   }
//得到缓存目录里的内容总大小
   public static  Long  getCacheLength(File filepath){
                           long length=0L;
                             File[] listfiles=filepath.listFiles();
                       for(int i=0;i<listfiles.length;i++){
                                 if(listfiles[i].isDirectory()){
                                      getCacheLength(listfiles[i]);
                                 }else{
                               length+=listfiles[i].length();
                                 }

                       }
        return length;

   }

  //清空缓存目录
   public static  void clearCacheFile(File file){
                   File[] files=file.listFiles();
                     for(int i=0;i<files.length;i++){
                             if(files[i].isDirectory()){
                                 clearCacheFile(files[i]);
                             }else{
                                 files[i].delete();
                             }
                     }
   }


     //发送内容

     //跳转Activity
    public static  <T>void redirectActivity(Context context,Class<T> className){
           Intent intent=new Intent(context,className);
           context.startActivity(intent);
    }
    public static  <T>void redirectActivity(Context context,Class<T> tClass,Map<String,Object> map){

                      Intent intent=new Intent(context,tClass);
        if(map==null||map.size()==0){
            context.startActivity(intent);
        }else{
            Iterator<Map.Entry<String,Object>>  maps=map.entrySet().iterator();
            while(maps.hasNext()){
                Map.Entry entry=maps.next();
                if(entry.getValue() instanceof  String){
                    intent.putExtra(entry.getKey().toString(),entry.getValue().toString());
                }else if(entry.getValue() instanceof  Integer){
                    intent.putExtra(entry.getKey().toString(),Integer.parseInt(entry.getValue().toString()));
                }else  if(entry.getValue() instanceof  Boolean){
                    intent.putExtra(entry.getKey().toString(),Boolean.parseBoolean(entry.getValue().toString()));
                }else if(entry.getKey() instanceof  Object){
                    intent.putExtra(entry.getKey().toString(), (Serializable) entry.getValue());
                }

            }
            context.startActivity(intent);
        }


    }




    public static void initStatus(Activity activity,int color) {
       SystemBarTintManager sm=new SystemBarTintManager(activity);
        sm.setStatusBarTintEnabled(true);
        sm.setStatusBarTintColor(activity.getResources().getColor(color));
    }



    public static boolean inMainProcess(Context context) {
        String packageName = context.getPackageName();
        String processName = getProcessName(context);
        return packageName.equals(processName);
    }
    /**
     * 获取当前进程名
     * @param context
     * @return 进程名
     */
    public static final String getProcessName(Context context) {
        String processName = null;

        // ActivityManager
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
        while (true) {
            for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) {
                if (info.pid == android.os.Process.myPid()) {
                    processName = info.processName;
                    break;
                }
            }
            // go home
            if (!TextUtils.isEmpty(processName)) {
                return processName;
            }

            // take a rest and again
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static byte[] Bitmap2Bytes(Bitmap bm){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h){
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) w / width);
        float scaleHeight = ((float) h / height);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        return newBmp;
    }

    public static void scaleFile(String srcpath,String outpath){

    }
    public  static Uri getUriForFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider
                    .getUriForFile(context.getApplicationContext(), "com.sendpo.zjx.sendpo.fileProvider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }

    public static String formatStrProblem(String str){
               if(TextUtils.isEmpty(str)){
                   return "";
               }
                String[] sps=str.split(",");
            if(sps==null||sps.length==0){
                return "";
            }
            String result="";
              for(String s:sps){
                  result=result+getProblem(Integer.parseInt(s))+" ";
              }
    return result;
    }
    public static String getProblem(Integer i){
           String  str="";
          switch (i){
              case 0:
              str="鱼尾纹、眼纹、额头皱纹、嘴角纹、川字纹、法令纹、表情纹";
                  break;
              case 1:
                  str="雀斑、真皮斑、铅汞中毒斑、老年斑、黄褐斑、色斑、荷尔蒙斑、蝴蝶斑、萎缩性癫斑、日晒斑、色斑、去黑斑";
                  break;
              case 2:
                  str="色素病变、激素脸、荧光脸";
                  break;
              case 3:
                  str="痘痘、痤疮、暗疮、痘坑痘印、脂肪粒、扁平疣、瘊子、老年疣";
                  break;
              case 4:
                  str="红黑痣、太田痣";
                  break;
              case 5:
                  str="过敏、油腻、干燥、牛皮癣、烫伤、晒伤、灼热、紫外线损伤、老化、瘙痒、疼痛、感染、毛囊发炎、发红、皮炎、破损、红疹、疤痕、脱屑、粗糙、浮肿、红血丝、去死皮、皮肤薄、脂肪团";
                  break;
              case 7:
                  str="肤色不均、紧致肌肤、肌肤无弹性、皮肤暗黄、去角质、脸部缺乏弹性";
                  break;
              case 8:
                  str="黑眼圈、泪沟、单眼皮、眼袋、眼部疲劳、眼角下垂";
                  break;
              case 9:
                  str="粉刺、白头、黑头、脱毛、毛孔堵塞、酒精鼻、毛孔污垢、毛孔粗大";
                  break;
              case 10:
                  str="V脸拉提、V脸雕塑、双下巴、瘦脸面部提升";
                  break;
              case 11:
                  str="低敏感、松垮、干涩缺水、无弹性、瘙痒异味、炎症、性交疼痛、老化";
                  break;
              case 12:
                  str="色素沉淀、脱毛";
                  break;
              case 13:
                  str="宫颈糜烂、宫寒不孕、";
                  break;
              case 14:
                  str="子宫下垂、激素分泌失调、温宫补巢";
                  break;
              case 15:
                  str="割双眼皮";
                  break;
              case 16:
                  str="纹眉、画眼线、绣眉、纹唇、纹眼线、纹唇线、浸唇";
                  break;
              case 17:
                  str="消美甲、美睫";
                  break;
              case 18:
                  str="肥胖纹、身体美白、排湿毒、身体脱毛";
                  break;

              case 19:
                  str="快速瘦腰、啤酒肚、大粗腿、消除肚腩、润滑肌肤、肥肚腩";
                  break;
              case 20:
                  str="妊娠纹、产后水肿、腰腹赘肉、淋巴排毒、局部肥胖、小腹凸起";
                  break;
              case 21:
                  str="洗牙、氟斑牙、四环素牙";
                  break;
              case 22:
                  str="牙齿塑形、矫正";
                  break;
              case 23:
                  str="补牙、牙齿缺失、拔牙、种植";
                  break;
              case 24:
                  str="口臭、口腔异味";
                  break;
              case 25:
                  str="劲椎病、腰椎病、肩周炎";
                  break;
              case 26:
                  str="推拿、按摩";
                  break;
              case 27:
                  str="关节炎、软组织损伤、筋骨摔伤";
                  break;
              case 28:
                  str="黑乳晕";
                  break;
              case 29:
                  str="下垂胸、去副乳、扁平胸、先天性胸部发育不良、小叶";
                  break;
              case 30:
                  str="增生、乳腺疏通、清除胸部结块、加快淋巴排毒";
                break;
              case 31:
                  str="臀缝黑、坐斑、消除橘皮、臀部发黑";
                  break;
              case 32:
                  str="肌肉松垮、麒麟臀、下垂臀、臀部凹陷、提臀";
                  break;
              case 33:
                  str="臀部冰凉、臀部两侧酸痛";
                  break;
              case 34:
                  str="排毒、刮痧、祛湿、火疗、拔罐、艾灸";
                  break;
              case 35:
                  str="降血脂、改善血液循环、清除体内自由基、漂浮水疗";
                  break;
              case 36:
                  str="器官受损修护";
                  break;
              case 37:
                  str="纹身、消洗纹身";
                  break;
              case 38:
                  str="纹眉、洗眉线、洗胎记";
                  break;
              case 39:
                  str="唇毛、胡须、胸毛、腋毛、腿毛、阴毛、体毛";
                  break;

          }
      return  str;
    }


//得到距离
    public static double getDistance(LatLng start, LatLng end) {

        double lon1 = (Math.PI / 180) * start.longitude;
        double lon2 = (Math.PI / 180) * end.longitude;
        double lat1 = (Math.PI / 180) * start.latitude;
        double lat2 = (Math.PI / 180) * end.latitude;

        // 地球半径
        double R = 6371;

        // 两点间距离 km，如果想要米的话，结果*1000就可以了
        double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1))
                * R;

        return d * 1000;
    }

    /**
     * 文件转base64字符串
     * @param file
     * @return
     */
    public static String fileToBase64(File file) {
        String base64 = null;
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            int length = in.read(bytes);

            base64 = android.util.Base64.encodeToString(bytes, 0, length, android.util.Base64.DEFAULT);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return base64;
    }

 }
